import sqlite3
import threading

class PySqlite3:

    def __init__(self, db_name='proxy.sqlite3'):

        self.db_name = db_name
        self.conn = sqlite3.connect(db_name, check_same_thread=False)
        self.cursor_lock = threading.Lock()       #新建一把锁
        self.cursor = self.conn.cursor()

    def insert(self, sql, info=None):
        with self.cursor_lock:     #with获取锁，并且自带解锁
            if info == None:
                self.cursor.execute(sql)
            else:
                self.cursor.execute(sql, info)
            self.conn.commit()

    def insert_many(self, sql, info):
        '''
        info : 是一个列表
        '''
        with self.cursor_lock:
            self.cursor.executemany(sql, info)
            self.conn.commit()

    def script(self, sql):
        with self.cursor_lock:
            self.cursor.executescript(sql)
            self.conn.commit()

    def fetch(self, sql):
        with self.cursor_lock:
            self.cursor.execute(sql)
            return self.cursor.fetchall()




